package com.epam.rd.classloader;

import java.io.File;

import javax.tools.JavaCompiler;
import javax.tools.ToolProvider;

public class ClassVersionUpdater {
    private String loadDir;
    private String className;
    private String fileName;
    private long lastUpdate;
    private JavaCompiler compiler;

    public ClassVersionUpdater(String dirPath, String className) {
        this.loadDir = dirPath;
        this.className = className;
        this.fileName = dirPath + className + ".java";
        this.compiler = ToolProvider.getSystemJavaCompiler();
    }

    public void join() throws ClassNotFoundException {
        File file = new File(fileName);
        System.out.println("Working with file: " + file.getAbsolutePath());
        lastUpdate = file.lastModified();
        moduleLoadFacade();
        while (true) {
            if (lastUpdate != file.lastModified()) {
                moduleLoadFacade();
                lastUpdate = file.lastModified();
            }
        }
    }

    private void moduleLoadFacade() throws ClassNotFoundException {
        System.out.println("Compile from file " + fileName);
        compiler.run(null, null, null, fileName);
        ClassLoader userDefinedCl = new MyLoader(
                ClassLoader.getSystemClassLoader(), loadDir);
        Class<?> updatedClass = userDefinedCl.loadClass(className);
        System.out.println("Result...");
        onClassUpdate(updatedClass);
    }

    public void onClassUpdate(Class<?> updatedClass) {
        try {
            Object obj = updatedClass.newInstance();
            System.out.println(obj.toString());
        } catch (InstantiationException e) {
            System.out.println(e.toString());
        } catch (IllegalAccessException e) {
            System.out.println(e.toString());
        }
    }
}